package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.expection.NameException;
import com.atguigu.gulimall.member.expection.PhoneException;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.vo.OauthUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册
     * @param vo
     */
    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置会员等级
        memberEntity.setLevelId(1L);
        //检查用户名和手机是否重复
        this.phoneExist(vo.getPhone());
        this.nameExsit(vo.getName());
        //设置会员名字
        memberEntity.setUsername(vo.getName());
        memberEntity.setMobile(vo.getPhone());
        String password = vo.getPassword();
        //加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(password);
        memberEntity.setPassword(encode);

        //执行保存
         this.save(memberEntity);

    }

    /**
     * 查询手机号是否重复
     * @param phone
     */
            @Override
    public void phoneExist(String phone)throws PhoneException {
        Integer integer = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (integer>1){
            throw new PhoneException();
        }
    }

    /**
     * 查询用户名是否重复
     * @param name
     */
    @Override
    public void nameExsit(String name) throws NameException{
        Integer integer = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", name));  if (integer>1){
            throw new NameException();
        }
    }

    /**
     * 用户登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String name = vo.getName();
        String password = vo.getPassword();
        //根据用户名查询用户信息
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", name).or().eq("mobile", name));
        if (memberEntity==null){
            return null;
        }else {
            //密码校验
            String password1 = memberEntity.getPassword();

            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, password1);
            if (matches){
                return memberEntity;
            }else {
                return null;
            }
        }
    }

    /**
     * 第三方登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity oauthLogin(OauthUser vo){
        //查询用户是否第一次登录
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", vo.getUid()));
        //判断是否为空
        if (memberEntity!=null){
            //不是第一次登录 更新令牌信息
            MemberEntity update = new MemberEntity();
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in());
            update.setId(memberEntity.getId());
            //跟新用户信息
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        }else {
            //为空 第一次登录
            MemberEntity memberEntity1 = new MemberEntity();
            //获取第三方用户基本信息
            Map<String,String> map = new HashMap<>();
            map.put("access_token",vo.getAccess_token());
            map.put("uid",vo.getUid());
            try {
                //获取用户信息
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", null, map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    String json = JSON.toJSONString(entity);
                    JSONObject parseObject = JSON.parseObject(json);
                    String name = parseObject.getString("name");
                    String gender = parseObject.getString("gender");
                    //把用户昵称添加到实体类中
                    memberEntity1.setNickname(name);
                    memberEntity1.setGender("m".equals(gender)?0:1);
                }
            }catch (Exception e){}
            memberEntity1.setAccessToken(vo.getAccess_token());
            memberEntity1.setUid(vo.getUid());
            memberEntity1.setExpiresIn(vo.getExpires_in());
            this.baseMapper.insert(memberEntity1);
            return memberEntity1;
        }
    }
}